import { ref } from 'vue'
import { adapter, request } from '@/request'
import is from '@/utils/is'
import { message } from 'ant-design-vue'
import { orderScheduleByGet } from '@/core/api/order'
import type { ServiceStatusEnum } from '@/core/enums/status'
import type { PlatformEnum } from '@/core/enums/platform'
import type { RequestWrapper } from '@/core/interfaces/common'
import type { Order } from '@/core/interfaces/order'

interface Params {
  orderNo: Order['orderNo']
}

export interface ScheduleTimeSpans {
  startTime: string
  endTime: string
  id: number
  orderId: number
  orderNo: string
  weekNo: number
  serviceStatus: ServiceStatusEnum
}

export interface ScheduleData {
  orderNo: string
  orderId: number
  schedulingTimes: number
  orderWords: OrderScheduleWords[]
  timespans: ScheduleTimeSpans[]
}

export interface OrderScheduleWords {
  id: number
  name: string
  orderId: number
  orderNo: string
  clientType: PlatformEnum
  scheduleStatuses: ScheduleWord[]
}

export interface ScheduleWord {
  id: number
  loading: boolean
  serviceStatus: ServiceStatusEnum
  weekNo: number
  orderWordId: number
}

export default function getOrderSchedule() {
  const service = adapter<RequestWrapper<ScheduleData>>(request)
  const loading = ref(false)
  const response = ref<Partial<ScheduleData>>({})

  const fetch = (params: Params) => {
    const { url, method } = orderScheduleByGet()
    loading.value = true

    return service({
      config: {
        url,
        method,
        params
      },
      callback: (res) => {
        response.value = res.data.data
      },
      error: (err) => {
        if (is.error(err)) {
          message.error(err.message)
          response.value = {}
        }
      },
      done: () => {
        loading.value = false
      }
    })
  }

  return [response, fetch, loading] as const
}
